//
//  BoxViewController.m
//  OrderSeat
//
//  Created by haiming on 13-10-11.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "BoxViewController.h"
#import "BoxCell.h"
#import "SeatConfirmViewController.h"
#import "LoginViewController.h"

@interface BoxViewController()
{
    int totalCount;
    int lastCount;
    int state;
    NSString *message;
}

@end

@implementation BoxViewController


- (id)initWithURL:(NSString *)url
{
    self = [super initWithNibClass:[BoxViewController class]];
    if (self) {
        _photoList = [[NSMutableArray alloc] initWithCapacity:5];
        _dataSource = [[BoxDataSource alloc] initWithVC:self];
        [_dataSource fetchSeatListWithURL:url];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[AppDelegate sharedInstance] showTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    [self setNavigationTitle:@"包厢"];
    
    _boxTV.delegate = self.dataSource;
    _boxTV.dataSource = self.dataSource;
    
    [UIView drawBorders:@[_topView,_downView]];
    [_orderTimeBtn setTitleForNormal:_orderTime];
    
    if (_seatState == 2) {
        [_btnDone setTitleColorNormal:[UIColor grayColor]];
        [_btnDone setBackgroundNormal:@"btn_enable.png"];
    }
}

- (IBAction)leftButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectedFinished
{
    totalCount = 0;
    for (NSDictionary *dic in _dataSource.seatList) {
        int count = [[dic objectForKey:@"selected"] intValue];
        totalCount += count;
    }
    
    self.totalCountLabel.text = [NSString stringWithFormat:@"已选择%d个座位",totalCount];
}

- (void)tapImageWithIndex:(NSInteger)index
{
    if (_photoList.count == 0) {
        for (NSDictionary *dic in _dataSource.seatList) {
            NSString *url = [dic objectForKey:@"image"];
            NSString *seatName = [dic objectForKey:@"zwname"];
            NSString *renshu = [dic objectForKey:@"renshu"];
            NSString *size = [dic objectForKey:@"size"];
            NSString *sheshi = [dic objectForKey:@"sheshi"];
            NSString *description = [NSString stringWithFormat:@"名称:%@   人数:%@人   面积:%@平方米   设施:%@",seatName,renshu,size,sheshi];
            
            MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            photo.caption = description;
            [_photoList addObject:photo];
        }
    }
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:index];

    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photoList.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photoList.count)
        return [_photoList objectAtIndex:index];
    return nil;
}

- (IBAction)doneAction:(id)sender
{
    if (state == 2) {
        [AppDelegate showMessage:message];
        return;
    }
    
    if (![self isSelectedSeat]) {
        [AppDelegate showMessage:@"请选择需要预定的座位！"];
        return;
    }
    
    if (![AppDelegate checkLoginWithDelegate:self]) return;
    
    [_dataSource.seatEntity setObject:_dataSource.seatList forKey:@"zuowei"];
    
    SeatConfirmViewController *confirmVC = [[SeatConfirmViewController alloc] initWithShopId:_shopId];
    confirmVC.shopEntity = self.data;
    confirmVC.seatEntity = _dataSource.seatEntity;
    
    [self.navigationController pushViewController:confirmVC animated:YES];
}

- (void)updateViews:(NSDictionary*)dictionary
{
    lastCount = [[dictionary objectForKey:@"shengyu"] intValue];
    state = [[dictionary objectForKey:@"zhuangtai"] intValue];
    message = [dictionary objectForKey:@"shuoming"];
    
    NSString *lastText = [NSString stringWithFormat:@"剩余：%d",lastCount];
    
    [self createRightButtonWithTitle:lastText background:@"" frame:CGRectMake(0, 0, 56, 30)];
    
    if (state == 2) {
        [_btnDone setTitleColorNormal:[UIColor grayColor]];
        [_btnDone setBackgroundNormal:@"btn_enable.png"];
    }
}

- (BOOL)isSelectedSeat
{
    for (NSDictionary *dic in _dataSource.seatList) {
        if ([[dic objectForKey:@"selected"] intValue] == 1) {
            return YES;
        }
    }
    return NO;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

@end

//=====================================================================================
#pragma===================================数据源实现=====================================
//=====================================================================================

@implementation BoxDataSource

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if(self) {
        self.viewController = viewController;
        _seatList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    
    return self;
}

- (void)fetchSeatListWithURL:(NSString*)url
{
    [SVProgressHUD show];
    [self get:url];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    
    CLog(@"response:%@",request.responseString);
    NSDictionary *json = [request.responseData JSONValue];
    
    self.seatList = [json objectForKey:@"zuowei"];
    [self.viewController updateViews:json];
    
    for (NSMutableDictionary *dic in _seatList) {
        [dic setObject:@"0" forKey:@"selected"];
    }
    
    [self.viewController.boxTV reloadData];
    self.seatEntity = [NSMutableDictionary dictionaryWithDictionary:json];
}

#pragma ===================加载tableview数据 Begin================================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _seatList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"BoxCell";
    BoxCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
    
    NSMutableDictionary *dictionary = [_seatList objectAtIndex:indexPath.row];
    [cell setContent:dictionary andIndex:indexPath.row];
    cell.delegate = _viewController;
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

#pragma ===================加载tableview数据 End================================================

@end


